﻿using Dao.User;
using ShareCode.Entity.User;
using Infrastructure.Attributes.Ioc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using ShareCode.Dto;
using ShareCode.KeyValue;
using ShareCode.Dto.User;
using Infrastructure.MyException;
using ShareCode.Util.Helper;
using Infrastructure.Util.Helper;
using ShareCode.Dto.User.Org.Admin;

namespace Bll.User
{
    /// <summary>
    /// by zhouxin
    ///</summary>
    [Component]
    public class UserOrgBll : BaseTreeBll<UserOrgEntity>
    {
        protected override UserOrgDao? Dao => (UserOrgDao?)base.Dao;

        [Autowired]
        public UserOrgDao SetDao { set { this._Dao = value; } }

        [Autowired]
        public UserAccountBll? AccountBll { get; set; }
        [Autowired]
        public UserEntryInformationBll? EntryInformationBll { get; set; }

        [Autowired]
        public UserOrgCountBll? OrgCountBll { get; set; }

        public async Task<long> AdminNewAsync(FileUploadDto<NewOrgDto> NewRecord)
        {

            try
            {
                await this.Dao!.AsTenant().BeginTranAsync();

                NewOrgDto entity = NewRecord.Model!;

                var models = await Dao.GetListAsync(t => t.Title == entity.OrgTitle || t.Domain == entity.OrgDomain);

                var myerr = new ShowUserLogicException("字段验证未能过");


                foreach (var model in models)
                {
                    if (model != default)
                    {
                        if (model.Title == entity.OrgTitle) { myerr.AddSonMessage(nameof(entity.OrgTitle), "系统内已存在"); }
                        if (model.Domain == entity.OrgDomain) { myerr.AddSonMessage(nameof(entity.OrgDomain), "系统内已存在"); }
                        //if (model.TheCode == entity.TheCode) { myerr.AddSonMessage("2", "系统内已存在"); }
                    }
                }

                

                var users = await AccountBll!.GetUserByNameOrMobileAsync(entity.UserName!, entity.Telephone!);

                foreach (var model in users)
                {
                    if (model.UserName == entity.UserName) { myerr.AddSonMessage(nameof(entity.UserName), "系统内已存在"); }
                    if (model.Mobile == entity.Telephone) { myerr.AddSonMessage(nameof(entity.Telephone), "系统内已存在"); }
                }

                if (myerr.SonErrs.Count > 0)
                {
                    throw myerr;
                }

                //写入企业信息
                var orgModel = new UserOrgEntity
                {
                    Title = entity.OrgTitle,
                    Domain = entity.OrgDomain,
                    Website = entity.OrgWebsite,
                    Remarks = entity.OrgRemarks,
                    Ico = UploadFileHelper.SaveFormFile(NewRecord.Files!, EnumFileUsage.OrgIcon),
                    TreeParentId= entity.OrgTreeParentId
                };

                var orgId = await TreeInsertSon(orgModel );

                if (!orgId)
                {
                    throw new Exception("写入企业信息失败");
                }

                //写入管理员信息
                var id = await AccountBll.Register(new UserRegisterDto
                {
                    Psw = string.IsNullOrEmpty(entity.Psw) ? "admin888" : entity.Psw,
                    UserName = entity.UserName,
                    Email = entity.Email,
                    Gender = entity.Gender,
                    Birthday = entity.Birthday,
                    Mobile = entity.Telephone,
                    Avatar = UploadFileHelper.SaveFormFile(NewRecord.Files!, EnumFileUsage.UserAvatar),
                });

                if (id < 1)
                {
                    throw new Exception("用户信息写入失败");
                }

                //写入入职信息
                var id2 = await EntryInformationBll!.InsertAsync(new UserEntryInformationEntity
                {
                    Email = entity.Email,
                    Gender = entity.Gender,
                    Birthday = entity.Birthday,
                    WorkNo = "-",
                    Telephone = entity.Telephone,
                    UserName = string.IsNullOrEmpty(entity.RealName) ? entity.UserName : entity.RealName,
                    AccountId = id,
                    OrgId = orgModel.Id,
                    IsAdmin = 1,
                    Avatar = UploadFileHelper.SaveFormFile(NewRecord.Files!, EnumFileUsage.UserAvatar, EnumFileUsage.UserEntryAvatar),
                });

                if (id2 < 1)
                {
                    throw new Exception("用户入职信息写入失败");
                }

                //写入统计表数据
                await OrgCountBll!.InsertAsync(new UserOrgCountEntity() { OrgId = orgModel.Id, EmployeeCount = 1 });

                await this.Dao.AsTenant().CommitTranAsync();

                return orgModel.Id;
            }
            catch (Exception ex)
            {
                await this.Dao!.AsTenant().RollbackTranAsync();

                if (ex is ShowUserLogicException sex)
                {
                    throw sex;
                }

                throw new ShowUserLogicException(ex.Message);
            }

        }

        public Task<PagingWithDataModel<AdminListDto>?> AdminListAsync(PagingDto? dto)
        {
            return Dao!.AdminListAsync(dto);
        }


    }
}
